package ServerStuff;

import java.io.IOException;
import java.net.HttpURLConnection;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Database.DatabaseConnector;
import ExceptionClasses.InvalidReviewerAuthenticationException;

/**
 * Servlet implementation class SubToServlet
 */
@WebServlet("/SubToServlet")
public class SubToServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("In subscribe to servlet");
		HttpSession session = request.getSession();
		 DatabaseConnector db = new DatabaseConnector();
		 String busName = request.getParameter("busName");
		 
		 System.out.println(busName);
		 
		 boolean logged;
		 
		 try{
			 	logged = (Boolean) session.getAttribute("subloggedIn");	 
		 	}
		 catch(NullPointerException e){
			 logged = false;
		 }
		 
			 if(logged)
			 {
				 String subUser = (String) session.getAttribute("subUser");
				 String subPassword = (String) session.getAttribute("subPass");
			 
				 System.out.println("Some one is logged");
				 System.out.println(subUser);
				 System.out.println(subPassword);
			 
				 try{
				 		db.subscribeToBusiness(subUser, subPassword, busName);
				 		System.out.println("you are subscribed");
						response.setStatus(HttpURLConnection.HTTP_ACCEPTED);
				 		
			 		}
				 catch (InvalidReviewerAuthenticationException e) 
			 			{
			 				e.printStackTrace();
							response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
			 			}
		 	}
		 	else
		 	{
			 	System.out.println("I'm so lost");
				response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
		 	}
	}

}
